<?php

namespace app\admin\controller\purchase;

use app\common\controller\Backend;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\purchase\EnterGoods;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Share extends Backend
{
    
    /**
     * Share模型对象
     * @var \app\common\model\purchase\Share
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Share;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['purchaseenter','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['purchaseenter','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','cost','explain','operator','company','status','purchase_enter_id']);
                $row->visible(['purchaseenter']);
				$row->getRelation('purchaseenter')->visible(['number','supplier_id']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();
            foreach ($list as &$v){
                $srow = Db::name('supplier')->where(array('id'=>$v['purchaseenter']['supplier_id']))->find();
                $v['supplier_nickname'] = $srow['nickname'];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids){

        $row = $this->model->find($ids);
        $list = Db::name('purchase_enter_goods')
            ->field('g.id as gid,pg.id,g.number,title,place_origin,specs,goods_num,unit_price,tax,remark,pg.goods_id,storehouse_id,unit,ht_price,share_price')
            ->alias('pg')
            ->where(array('purchase_enter_id'=>$row['purchase_enter_id']))
            ->join('goods g','pg.goods_id = g.id')
            ->select();
        foreach ($list as $k=>$v){
            $list[$k]['buy_price'] = round($v['goods_num']*($v['ht_price']/((100+$v['tax'])/100)),2);
            $list[$k]['tax_all'] = round(($v['ht_price']/($v['tax']+100))*$v['tax']*$v['goods_num'],2);
        }
        $this->assign('com_fare',$row['cost']);
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function printing($ids){
        $row = $this->model->find($ids);
        $list = Db::name('purchase_enter_goods')
            ->field('g.id as gid,pg.id,g.number,title,place_origin,specs,goods_num,unit_price,tax,remark,pg.goods_id,storehouse_id,unit,ht_price,share_price')
            ->alias('pg')
            ->where(array('purchase_enter_id'=>$row['purchase_enter_id']))
            ->join('goods g','pg.goods_id = g.id')
            ->select();
        foreach ($list as $k=>$v){
            $list[$k]['buy_price'] = round($v['goods_num']*($v['ht_price']/((100+$v['tax'])/100)),2);
            $list[$k]['tax_all'] = round(($v['ht_price']/($v['tax']+100))*$v['tax']*$v['goods_num'],2);
        }
        $hrow = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();
        $this->assign('com_fare',$row['cost']);
        $this->assign('row',$row);
        $this->assign('hrow',$hrow);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function cancelbill($ids = null){
        if(!$this->request->isAjax()){
            $this->error('非法操作');
        }
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }

        $row = $this->model->find($ids);
        if ($row['status'] !=1){
            $this->error('状态异常');
        }
        $list = Db::name('purchase_enter_goods')
            ->field('g.id as gid,pg.id,g.number,title,place_origin,specs,goods_num,unit_price,tax,remark,pg.goods_id,storehouse_id,unit,ht_price,share_price')
            ->alias('pg')
            ->where(array('purchase_enter_id'=>$row['purchase_enter_id']))
            ->join('goods g','pg.goods_id = g.id')
            ->select();
        Db::startTrans();
        try {
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

            foreach ($list as $v) {
                $EnterGoods = new EnterGoods;

                $EnterGoods->save(array(
                    'share_price' => 0,
                    'cost_price' => $v['unit_price'],
                ), array('id' => $v['id']));

                $GoodsHouseStock = new GoodsHouseStock;
                $groww = $GoodsHouseStock->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                $balance = $groww['balance']-$v['share_price'];//减去分摊的费用
                $weighting_cost = $balance/$groww['stock'];

                $GoodsHouseStock = new GoodsHouseStock;
                $GoodsHouseStock->save(array(
                    'weighting_cost'=>$weighting_cost,
                    'balance'=>$balance,
                ),array('id'=>$groww['id']));


                    //库存变化
                Db::name('goods_stock_log')->insert(array(
                    'goods_id'=>$v['goods_id'],
                    'createtime'=>time(),
                    'number'=>$row['number'],
                    'type'=>'采购入库分摊单',
                    'source'=>13,
                    'type_id'=>$row['id'],
                    'enter_num'=>0,
                    'before_num'=>0,
                    'now_num'=>$groww['stock'],
                    'storehouse_id'=>$row['storehouse_id'],
                    'controller'=>'purchase/share',
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'company'=>$group['name'],
                    'operator'=>session('admin')['nickname'],
                    'final_cost'=>$balance/$groww['stock'], //记录的金额应该是入库的加权单价
                    'bill_cost'=>$v['share_price'], //记录的金额应该是入库的采购成本
                    'balance'=>$balance, //记录的金额当前库存总额
                    'is_cancel'=>1,
                ));
            }

            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 13,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/share',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));


            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'purchase/share',
                'source_id'=>$ids,
                'source'=>13,
                'remark'=>'采购分摊单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            //修改平摊单据状态
            $this->model->save(array('status'=>2),array('id'=>$ids));

            //修改 入库单的状态
            $model = new \app\common\model\purchase\Enter();
            $model->save(array('is_share' => 0), array('id' => $row['purchase_enter_id']));
            Db::commit();
            return  array(
                'code'=>1,
                'msg'=>'成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

}
